package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public void delete(Long id) {

        employeeMapper.deleteByPrimaryKey(id);

    }

    @Override
    public void save(Employee employee, Long[] ids) {

        //对密码进行加密
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());
        //保存之后,employee就有id
        employeeMapper.insert(employee);

        if (ids != null && ids.length>0){

            //关联关系
            for (Long roleId : ids){

                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {


        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listALL() {

        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {

        employeeMapper.updateByPrimaryKey(employee);

        //删除关系
        employeeMapper.deleteRelation(employee.getId());

        if (ids != null && ids.length>0){

            //关联关系
            for (Long roleId : ids){

                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {

       /* int count = employeeMapper.selectForCount(qo);
        if (count == 0){

            return new PageResult<>(qo.getCurrentPage(),qo.getPageSize() , Collections.emptyList(), count);

        }

        //获取总页数
        int totalPage = count % qo.getPageSize() == 0
                ? count / qo.getPageSize() : count / qo.getPageSize() + 1;
        //判断当前页是否大于总页数,如果是,把总页数作为当前页来查询分页结果集

        if (qo.getCurrentPage() > totalPage){

            qo.setCurrentPage(totalPage);
        }
*/
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);

        return new PageInfo<>(employees);

    }

/*
    @Override
    public Employee login(String username, String password) {

        //查询数据库中是否有匹配的数据
        if (!StringUtils.hasText(username)){

            throw new RuntimeException("用户名不能为空");
        }

        if (!StringUtils.hasText(password)){

            throw new RuntimeException("密码不能为空");
        }

        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee==null){

            throw new RuntimeException("用户名或密码错误");
        }

        if (!employee.isStatus()){

            throw new LogicException("账号被禁用,请联系管理员");
        }
        return employee;
    }
*/


    @Override
    public void updateAll(String oldPassword, String newPassword) {

        Employee employee = UserContext.getCurrentUser();
        System.out.println(employee.getPassword());
        //查询数据库中是否有匹配的数据
        if (oldPassword==null || oldPassword.trim().length()==0){

            throw new LogicException("旧密码不能为空");
        }

        if (newPassword==null || newPassword.trim().length()==0){

            throw new LogicException("新密码不能为空");
        }


        if (!oldPassword.equals(employee.getPassword())){

            System.out.println(oldPassword);

            throw new LogicException("原密码错误");
        }



        employee.setPassword(newPassword);

        employeeMapper.selectByoldPasswordAndnewPassword(employee);
    }

    @Override
    public void insert1(Employee employee) {

        employeeMapper.selectByoldPasswordAndnewPassword(employee);
    }

    @Override
    public void batchDelete(Long[] ids) {


        //判断ids数组中是否为空,长度是否为0
        if (ids!=null && ids.length>0){
            employeeMapper.batchDelete(ids);
        }
    }

    @Override
    public Workbook exportXLs() {

        //查询所有员工
        List<Employee> employees = employeeMapper.selectAll();

        //使用poi创建一个excel
        Workbook wb = new HSSFWorkbook();
        //创建excel中的表
        Sheet sheet = wb.createSheet("员工通讯录");

        //创建标题行数据,从0开始
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        for (int i = 0; i < employees.size(); i++) {

            //每个员工创建一行数据
            Employee employee = employees.get(i);

            //创建一行数据,从0开始
            row = sheet.createRow(i+1);

            //创建单元格写入内容到单元格
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());


        }

        return wb;
    }

    @Override
    public void importXLs(MultipartFile file) throws IOException {

        //读取上传的文件,并且封装成一个Workbook对象
        HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第0张sheet表
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();

        //标题行不需要读,lastRowNum 是索引 ,需要=
        for (int i = 1; i <= lastRowNum; i++) {

            //获取每一行数据

            //文本类型单元格写数字 有绿色箭头
            Row row = sheet.getRow(i);
            Employee employee = new Employee();

            //if (row.getCell(0)==null || row.getCell(0)==null){  //判断空值问题,用户名或邮箱其中一个为空就不读取

            //    break; //判空
            //}
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());

            Cell cell = row.getCell(2);
            //判断单元格格式
            if (cell.getCellType() == CellType.NUMERIC){   //作为数字单元格读取

                employee.setAge(((int) row.getCell(2).getNumericCellValue()));

            }else {

                employee.setAge(Integer.valueOf(( row.getCell(2).getStringCellValue())));
            }

            employeeMapper.insert(employee);

            //使用service调用
            //save(employee,null);
        }
        //System.out.println(lastRowNum);
    }


    @Override
    public Employee selectByName(String name,Long id) {

        Employee employee;

        //当id为空时
        if (id==null){

            //查询数据库的name
            employee = employeeMapper.selectByName(name);


        }else {

            //获取id,判断数据库的name和浏览器输入的是否一致
            Employee employee1 = employeeMapper.selectByPrimaryKey(id);
            if (employee1.getName().equals(name)){

                //如果一样就返回null
                return null;
            }else {

                //否则返回数据库中的name
                employee = employeeMapper.selectByName(name);
            }
        }
        return employee;

    }

    @Override
    public Employee selectAndName(String name) {

        return employeeMapper.selectAndName(name);
    }

    @Override
    public void updateOne(Employee employee) {

        employeeMapper.updateOne(employee);
    }

    @Override
    public List<Employee> selectBySeller(String... sns) {
        return employeeMapper.selectBySeller(sns);
    }

}
